import { _decorator, BoxCollider, Component, director, ITriggerEvent, Node } from 'cc';
import { Constand } from './Constant';
import { PoolMananger } from './PoolMananger';
const { ccclass, property } = _decorator;

@ccclass('Bullet')
export class Bullet extends Component implements IDamage {
    @property
    public damage: number = 1;
    private _speed = 0;

    private _isEnemy = false;
    private _direction = Constand.Direction.MIDDLE;
    onEnable() {
        const collider = this.getComponent(BoxCollider);
        collider.on('onTriggerEnter',this._onTriggerEnter, this);
    }

    onDisable(): void {
        const collider = this.getComponent(BoxCollider);
        collider.off('onTriggerEnter',this._onTriggerEnter, this);
    }

    private _onTriggerEnter(event: ITriggerEvent) {
        PoolMananger.getInstance().putNode(this.node);
    }

    update(deltaTime: number) {
        const pos = this.node.position;
        if(this._isEnemy){
            const moveLength = pos.z + this._speed * 0.5;
            this.node.setPosition(pos.x, pos.y, moveLength)
            if(moveLength > 60){
                PoolMananger.getInstance().putNode(this.node);
            }
        }else{
            const moveLength = pos.z - this._speed;
            switch(this._direction){
                case Constand.Direction.LEFT:
                    this.node.setPosition(pos.x - this._speed * 0.2, pos.y, moveLength)
                    break;
                case Constand.Direction.RIGHT:
                    this.node.setPosition(pos.x + this._speed * 0.2, pos.y, moveLength)
                    break;
                default:
                    this.node.setPosition(pos.x, pos.y, moveLength)
            }
            this.node.setPosition(pos.x, pos.y, moveLength)
            if(moveLength < -60){
                PoolMananger.getInstance().putNode(this.node);
            }
        }
    }

    setSpeed(value: number, isEnemy: boolean, direction: number = Constand.Direction.MIDDLE){
        this._speed = value;
        this._isEnemy = isEnemy;
        this._direction = direction;
    }
}


